package com.hyh.media;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

import com.hyh.data.PlatModule;
import com.hyh.speex.Speex;

/**
 * Created by Administrator on 2019/1/27.
 */

public class AudioRecordUtil {

    private Speex speex;
    private AudioRecord audioRecord;
    private static AudioRecordUtil audioRecordUtil;
    private boolean recordFlag = false;


    private AudioRecordUtil(){
        speex = Speex.getInstance();
        audioRecord = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION,8000, AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT,speex.getFrameSize());
    }

    public static synchronized AudioRecordUtil getInstance(){
        if(audioRecordUtil==null){
            audioRecordUtil = new AudioRecordUtil();
        }
        return audioRecordUtil;
    }

    public void startRecord(){
        if(!recordFlag){
            recordFlag = true;
            audioRecord.startRecording();
            new ReadThread().start();
        }
    }

    public void stopRecord(){
        if(recordFlag){
            recordFlag = false;
            audioRecord.stop();
        }
    }

    private class ReadThread extends Thread{
        @Override
        public void run() {
            short shortBuf[] = new short[speex.getFrameSize()];
            short echoBuf[] = new short[speex.getFrameSize()];
            byte buf[] = new byte[speex.getFrameSize()];
            while (recordFlag){
                int len = audioRecord.read(shortBuf,0,speex.getFrameSize());
                speex.capture(shortBuf,echoBuf);
                int size = speex.encode(echoBuf,0,buf,len);
                byte data[] = new byte[size];
                System.arraycopy(buf,0,data,0,size);
                PlatModule.getInstance().transferFrame(data);
            }
        }
    }



}
